﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using WebApiVersionControl.Models.Untity;

namespace WebApiVersionControl.Controllers
{
    public class UploadImageController : Controller
    {
        // GET: UploadImage
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadPhotos()
        {
            var filesCount = HttpContext.Request.Files.Count;
            if (filesCount == 0)
            {
                throw new ArgumentNullException("请上传图片");
            }
            //图片格式
            string[] Format = { ".BMP", ".TIFF", ".GIF", ".PNG", ".JPEG", ".PSD", ".JPG", ".TGA", ".EPS" };
            for (int i = 0; i < filesCount; i++)
            {
                var imageName = HttpContext.Request.Files[i].FileName;
                string suffiexName = Path.GetExtension(imageName).ToLower();
                if (!Format.Contains(suffiexName))
                {
                    throw new ArgumentNullException("请上传正确的图片格式");
                }
                string imageToBase64;
                using (var stream = HttpContext.Request.Files[0].InputStream)
                {
                    byte[] bs = new byte[stream.Length];
                    stream.Read(bs, 0, bs.Length);
                    stream.Seek(0, SeekOrigin.Begin);
                    imageToBase64 = Convert.ToBase64String(bs);
                }
                try
                {
                    //图片大小
                    int imglength = HttpContext.Request.Files[i].ContentLength;
                    string imgtype = HttpContext.Request.Files[i].ContentType;
                    //插入数据库代码
                }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
                catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
                {
                    throw new ArgumentNullException("图片上传错误");
                }
            }
            return APIModel.success("图片上传成功！");
        }


        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="annotationid">id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DownloadFile(string annotationid)
        {
            if (annotationid.IsEmpty())
            {
                return APIModel.error("请输入下载文件");
            }
            string fileName = null, data = null;
            DataTable entityResult = new DataTable();
            foreach (var item in entityResult.Rows)
            {
                //fileName = item.Contains("filename") ? item["filename"].ToString() : null;
                //data = item.Contains("documentbody") ? item["documentbody"].ToString() : null;
            }
            if (fileName.IsEmpty() || data.IsEmpty())
            {
                return APIModel.error("文件未找到或者文件已迁移");
            }
            string filePath = System.Web.HttpContext.Current.Server.MapPath("/Annex");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            string path = filePath + "\\" + fileName;
            using (FileStream stream = new FileStream(path, FileMode.Create))
            {
                byte[] bs = Encoding.UTF8.GetBytes(data);
                stream.Write(bs, 0, bs.Length);
            }
            var fileStream = new FileStream(path, FileMode.Open);
            using (HttpResponseMessage responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK))
            {
                responseMessage.Content = new StreamContent(fileStream);
                responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = HttpUtility.UrlEncode(Path.GetFileName(fileName))
                };
                if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    return APIModel.error("下载文件出错");
                }
            }
            return APIModel.success(null, "下载成功");
        }
    }
}